package work5.CourseManagement;

import work5.SqlConnection;
import work5.StudentInfManagement.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CourseDao {
    private static Statement stmt = null;
    private static ResultSet rs = null;
    private static Connection conn = SqlConnection.getConn();

    public static void insert(Course s) {

        String sql = "insert into course (id,name,credit)" +
                "values (?,?,?)";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setInt(1, s.getId());
            p.setString(2, s.getName());
            p.setDouble(3, s.getCredit());
            p.executeUpdate();

        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }
    }

    public static void delete(Course s) {
        String sql="delete from course where id=?";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setInt(1, s.getId());
            p.executeUpdate();
        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }
    }

    public static void change(Course s) {

        //update tb_emp set name='张三' ,update_time=now() where id=1;
        String sql="update course set name=?,credit=? where id=?";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setString(1, s.getName());
            p.setDouble(2, s.getCredit());
            p.setInt(3, s.getId());
            p.executeUpdate();
        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }




    }

    public static List<Course> find(Course s) {//-1通过名字查找
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            System.out.println("无法创建 Statement 对象");
            e.printStackTrace();
        }



        String sql;
        if (s.getId() == 0) {
            sql = "select * from course ;";
        }
        else if(s.getId()==-1){
            sql = "select * from course where name="+s.getName() +";";
        }  else {
            sql = "select * from course where id=" + s.getId()+";";
        }
        List<Course> results = new ArrayList<>();
        try {
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                Double credit = rs.getDouble("credit");
                results.add(new Course(id, name, credit));
            }
        } catch (SQLException e) {
            System.out.println("输入有误请重新输入");
        }

        try {
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return results;
    }


}
